package com.changeover.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.changeover.dao.IDao;
import com.changeover.gwt.shared.model.IModel;

public abstract class AbstractDao<T extends IModel> implements IDao<T> {

//    @Autowired
    private SessionFactory sessionFactory;

    public List<T> getAll() {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from " + getEntityClass().getName());
        @SuppressWarnings("unchecked")
        List<T> list = query.list();
        return list;
    }

    public T get(Serializable id) {
        Session session = sessionFactory.getCurrentSession();
        @SuppressWarnings("unchecked")
        T entity = (T) session.get(getEntityClass(), id);
        return entity;
    }

    public void delete(T entity) {
        Session session = sessionFactory.getCurrentSession();
        session.delete(entity);
    }

    public void delete(Serializable id) {
        Session session = sessionFactory.getCurrentSession();
        session.delete(get(id));
    }

    public void saveOrUpdate(T entity) {
        Session session = sessionFactory.getCurrentSession();
        session.saveOrUpdate(entity);
    }

    abstract protected Class<T> getEntityClass();

}
